package xyz.iguilty.workflow.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.iguilty.workflow.core.service.WorkFlowActionService;
import xyz.iguilty.workflow.core.service.WorkFlowInfoService;
import xyz.iguilty.workflow.model.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/flow")
@Api(tags = "流程中心")
public class WorkFlowController {
    @Autowired
    private WorkFlowInfoService workFlowInfoService;
    @Autowired
    private WorkFlowActionService workFlowActionService;


    @ApiOperation(value = "统一代办")
    @GetMapping("/todo")
    public PageInfo<TaskInfo> todo(TaskCriteria criteria,
                                   @RequestParam(name="pageNumber", defaultValue="1")Integer pageNumber,
                                   @RequestParam(name="pageSize", defaultValue="10")Integer pageSize) {
        return workFlowInfoService.tasksTodo(criteria,pageNumber,pageSize);
    }

    @ApiOperation(value = "我处理的")
    @GetMapping("/iResolved")
    public PageInfo<TaskInfo> iResolved(TaskCriteria criteria,
                                    @RequestParam(name="pageNumber", defaultValue="1")Integer pageNumber,
                                    @RequestParam(name="pageSize", defaultValue="10")Integer pageSize) {
        return workFlowInfoService.tasksResolved(criteria,pageNumber,pageSize);
    }

    @ApiOperation(value = "我发起的")
    @GetMapping("/iStart")
    public PageInfo<ProcessInstanceInfo> iStart(ProcessInstanceCriteria criteria,
                                            @RequestParam(name="pageNumber", defaultValue="1")Integer pageNumber,
                                            @RequestParam(name="pageSize", defaultValue="10")Integer pageSize) {
        return workFlowInfoService.process(criteria,pageNumber,pageSize);
    }

    @ApiOperation(value = "进度跟踪")
    @GetMapping(value = "/track")
    public void track(String processInstanceId, HttpServletResponse response) throws IOException {
        InputStream inputStream = workFlowInfoService.track(processInstanceId);
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.copy(inputStream, outputStream);
    }

    @ApiOperation(value = "处理任务")
    @PostMapping(value = "/deal")
    public String deal(@RequestBody TaskForm taskForm){
        if (taskForm.getUserId()==null){
            return "请输入处理人id";
        }
        workFlowActionService.complete(taskForm, taskForm.getUserId());
        return "处理成功";
    }

}
